import { defineConfig, loadEnv } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import { visualizer } from 'rollup-plugin-visualizer'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import globalStyle from '@originjs/vite-plugin-global-style'

const getPath = (path) => {
    return fileURLToPath(new URL(path, import.meta.url))
}

export default defineConfig(({ command, mode }) => {
    const env = loadEnv(mode, process.cwd(), 'JPAAS_');
    let moduleConfig = {
        form:'@lowcode/jpaas-form-lib',
        base:'@lowcode/jpaas-base-lib',
        share:'@lowcode/jpaas-share-component',
    }
    return {
        plugins: [
            vue(),
            globalStyle({
                lessEnabled: true
            }),
            visualizer({
                gzipSize: true,
                brotliSize: true,
                emitFile: false,
                filename: "preview.html",
                open: false
            }),
            viteCompression()
        ],
        resolve: {
            alias: {
                extensions: ['.vue'],
                '@': getPath('./src'),
                '@public': getPath('./public'),
                'vue': 'vue/dist/vue.esm-bundler.js'
            }
        },
        server: {
            port: 8110,
            host: '0.0.0.0',
            // 代理配置
            proxy: {
                '/api': {
                    target: 'http://192.168.1.126:8000/api',
                    changeOrigin: true, // 允许跨域
                    rewrite: (path) => path.replace(/^\/api/, '')
                }
            }
        },
        optimizeDeps: {
            exclude:moduleConfig[mode]?[moduleConfig[mode]]:[],
        },
        css: {},
        base: env.JPAAS_BASE_URL,
        build: {
            rollupOptions: {
                output: {
                    assetFileNames: "[hash]-[name].[ext]",
                    chunkFileNames: "[hash]-[name].js",
                   /* manualChunks(id) {
                        if (id.includes('node_modules')) {
                            return id.toString().split('node_modules/')[1].split('/')[0].toString();
                        }
                    }*/
                },
            },
            assetsInlineLimit: 4096,
            outDir: 'dist',
            assetsDir: 'assets',
            cssCodeSplit: false,
            sourcemap: false,
            minify: "terser",
            terserOptions: {
                compress: {
                    drop_console: true,
                    drop_debugger: true
                }
            }
        },
        envPrefix: 'JPAAS_',
    }
})
